<template>
  <div class="main">
    <!-- 检索区,查询表单 -->
    <div class="search">
      <!-- 表单组件 -->
      <el-form
          :inline="true"
          ref="searchFromRef"
          :model="pm"
          class="searchForm"
      >
        <!-- 表单项 -->
        <el-form-item label="项目名称:" style="width: 200px" prop="projectName">
          <el-input placeholder="请输入项目名称" v-model="pm.projectName" />
        </el-form-item>

        <!-- 表单项 -->
        <el-form-item label="实验导师：" style="width: 200px" prop="projectLeaderId">
          <el-input placeholder="输入实验导师：" v-model="pm.projectLeaderId" />
        </el-form-item>

        <!--        时间筛选范围-->
        <el-form-item label="创建时间：" style="width: 320px" prop="projectTime">
          <el-date-picker
              v-model="pm.projectTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="项目状态：" style="width: 200px" prop="projectStatus">
          <el-select v-model="pm.projectStatus" placeholder="请选择状态">
            <el-option label="进行中" value="进行中" />
            <el-option label="未开始" value="未开始" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 按钮 -->
      <el-button
          color="#909399"
          plain
          :icon="Search"
          @click="search"
          style="width: 75px"
      >查询</el-button
      >
      <el-button
          color="#e6a23c"
          plain
          :icon="Refresh"
          @click="resetSearch"
          style="width: 75px"
      >重置</el-button
      >
    </div>

    <!-- 数据展示区 -->
    <div class="data">
      <!-- 数据展示区 -->
      <div class="grid">
        <el-row :gutter="20">
          <el-col
              v-for="(item, index) in tableData"
              :key="index"
              :span="8"
          >
            <el-card shadow="hover" style="margin-bottom: 10px">
              <div class="card-header">
                <span class="project-name">{{ item.projectName }}</span>
                <span class="project-leader">导师编号: {{ item.projectLeaderId }}</span>
              </div>
              <div class="project-introduction">
                {{ item.projectIntroduction }}
              </div>
              <div class="project-details">
                <span class="date-time">开始时间: {{ item.projectStartTime }} &nbsp;&nbsp;&nbsp;&nbsp; 结束时间: {{ item.projectEndTime }}</span>
                <span class="participation">已报人数: {{ item.studentParticipationCount }}</span>
              </div>
              <div class="project-actions">
                <el-button
                    :class="statusMap[item.projectStatus].type"
                    plain
                >
                  {{ statusMap[item.projectStatus].text }}
                </el-button>
                <el-button
                    color="#409eff"
                    :icon="Edit"                style="width: 70px"
                    @click="edit(item)"
                    plain
                >预约</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pageInfo.pageNum"
            v-model:page-size="pageInfo.size"
            :page-sizes="[10, 15, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
            background
            @size-change="paginate"
            @current-change="paginate"
        />
      </div>
    </div>
  </div>
  <el-dialog
      v-model="show"
      :title="title"
      width="800"
      draggable
      :close-on-click-modal="false"
      @close="close"
  >
    <el-form ref="sfRef" :model="pfm" :rules="rules" label-width="100" style="width: 100%; margin: 0 auto;">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
              label="项目名称"
              prop="projectName"
              :rules="[
              {
                required: true,
                message: '请输入实验名称',
                trigger: 'blur',
              },
            ]"
          >
            <el-input v-model="pfm.projectName" />
          </el-form-item>

          <el-form-item label="项目指导老师:" prop="projectLeaderId">
            <el-input v-model="pfm.projectLeaderId" />
          </el-form-item>
          <el-form-item label="开始时间：" prop="projectStartTime">
            <el-date-picker
                v-model="pfm.projectStartTime"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目状态："  prop="projectStatus">
            <el-select v-model="pfm.projectStatus" placeholder="请选择状态">
              <el-option label="进行中" value="进行中" />
              <el-option label="未开始" value="未开始" />
              <el-option label="已完成" value="已完成" />
              <el-option label="已取消" value="已取消" />
            </el-select>
          </el-form-item>
          <!--          参与学生人数-->
          <el-form-item label="实验人数："  prop="studentParticipationCount">
            <el-input v-model="pfm.studentParticipationCount" />
          </el-form-item>

          <el-form-item label="结束时间：" prop="projectEndTime">
            <el-date-picker
                v-model="pfm.projectEndTime"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="项目简介：" prop="projectIntroduction">
            <el-input v-model="pfm.projectIntroduction" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 对话框按钮，#插槽: 组件空出来，允许用户更改组件内容。由组件使用者定义 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 发布实验 对话框 -->
</template>

<script setup>
import projectApi  from "@/api/ProjectApi.js";
import { reactive, ref } from "vue";
import { onMounted, toRaw, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import  userNameApi from "@/api/userNameApi";
import dayjs from "dayjs"; // 用于日期处理
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Refresh,
  Plus,
} from "@element-plus/icons-vue";
import adminApi from "@/api/AdminApi.js";

// 定义状态映射
const statusMap = {
  '进行中': { type: 'custom-primary', text: '进行中' },
  '未开始': { type: 'custom-info', text: '未开始' },
  '已完成': { type: 'custom-success', text: '已完成' },
  '已取消': { type: 'custom-danger', text: '已取消' }
};
// 取出缓存中的内容userNameApi.get()
const userName = getUserName();
function getUserName() {
  return userNameApi.get();
}
//当组件挂载结束之后调用
onMounted(() => {
  search();
  document.title = "植物表型数据管理系统";
});

//响应式对象
const tableData = ref([]);
function paginate() {
  search();
}

// 分页信息
const pageInfo = ref({
  pageNum: 1,
  size: 10,
  total: 0,
});

// 当页码和页码大小改变时触发

function search() {
  let params = pm.value; // 查询条件
  // 检查 projectTime 数组是否包含两个日期字符串
  if (Array.isArray(pm.value.projectTime) && pm.value.projectTime.length === 2) {
    params.projectStartTime = pm.value.projectTime[0];
    params.projectEndTime = pm.value.projectTime[1];
  } else {
    params.projectStartTime = "";
    params.projectEndTime = "";
  }
  const time = pm.value.projectTime;
  projectApi
      .findAll(pageInfo.value.pageNum, pageInfo.value.size, params)
      .then((result) => {
        console.log(result);
        if (result.code == 200) {
          tableData.value = result.data.records;
          pageInfo.value.total = result.data.total;
          pageInfo.value.pageNum = result.data.pages;
          pageInfo.value.size = result.data.size;
        }
      });
  pm.value.projectTime = time;
  console.log(time);
}

// 搜索条表单双向数据绑定
const pm = ref({
  projectName: "",
  projectLeaderId: "",
  projectIntroduction: "",
  projectTime:[],
  projectStatus: "",
  studentParticipationCount: "",
});

// // 表单实例的引用
let searchFromRef;
function resetSearch() {
  // 重置查询表单
  searchFromRef.resetFields();
}
// 定义表格实例
let tableRef;
//当点击表格时触发
function rowClick(row) {
  tableRef.toggleRowSelection(row);
}


// 对话框是否显示
const show = ref(false);

// 定义对话框内容
const plainFormModel = ref({
  projectName: "",
  projectIntroduction: "",
  projectLeaderId: "",
  projectStartTime:"",
  projectEndTime:"",
  projectStatus: "",
  studentParticipationCount: "",
});
// 对话框内容别名
const pfm = plainFormModel;

// 对话框标题
const title = ref("新增实验信息");
// 弹出新增
function add() {
  show.value = true;
  title.value = "新增实验信息";
  let project = pfm.value;
  project.projectId = "";
}
// 提交表单
function submitForm() {
  let project = pfm.value;
  if (project.projectId !== "" ) {
    //修改
    submitEdit(project);
  } else {
    //发布实验
    submitAdd(project);
  }
}

// 新增逻辑
function submitAdd(project) {
  projectApi.save(project).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "新增成功",
      });
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
  show.value = false;
}

let sfRef;
// 关闭对话框，重置表单
function close() {
  sfRef.resetFields();
}
const appointInfo = ref ({
  projectId: "",
  contactInfo: ""
});
// 修改操作
function edit(row) {
  // 判断是否选中了要删除的记录
  // 记录row的id
  appointInfo.value.projectId = row.projectId;
  appointInfo.value.contactInfo = userName;
  console.log(appointInfo.value);
  // 获取调用的用户信息 userName
    ElMessageBox.confirm("是否确定预约选中的实验吗？", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      projectApi
          .appointment(appointInfo.value)
          .then((resp) => {
            console.log(resp);
            if (resp.code == 200) {
              ElMessage({
                type: "success",
                message: "预约成功",
              });
              search(); //刷新
            }
            else {
              ElMessage({
                type: "error",
                message: resp.msg,
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "预约操作取消",
            });
          });
    });
}


//表头样式
function headerCellStyle() {
  return {
    background: " #f4f4f5",
    textAlign: "center",
    color: "#909399",
  };
}

// 切换状态
function switchChange2(row) {
  let project = toRaw(row);
  user.locked = user.locked === true ? 0 : 1;
  projectApi.updataByState(project).then((resp) => {
    if (resp.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      // project.locked = project.locked === 0 ? 1 : 0;
      search();
    } else {
      ElMessage({
        type: "error",
        message: resp.msg,
      });
    }
  });
}

//头像上传成功时的回调函数
function avatarSuccess(resp, file) {
  if (resp.code == 200) {
    pfm.value.imagePath = resp.data;
  }
}

// 定义自定义验证规则：开始时间必须大于当前时间
const validateStartTime = (rule, value, callback) => {
  const now = dayjs().format("YYYY-MM-DD");
  if (value && dayjs(value).isBefore(now)) {
    callback(new Error("开始时间必须大于当前时间"));
  } else {
    callback();
  }
};

// 定义自定义验证规则：开始时间不能大于结束时间
const validateEndTime = (rule, value, callback) => {
  const startTime = pfm.value.projectStartTime;
  if (startTime && value && dayjs(startTime).isAfter(value)) {
    callback(new Error("开始时间不能大于结束时间"));
  } else {
    callback();
  }
};
// 表单验证规则
const rules = {
  projectName: [
    {
      required: true,
      message: '请输入实验名称',
      trigger: 'blur',
    },
  ],
  projectStartTime: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: 'change',
    },
    { validator: validateStartTime, trigger: 'change' },
  ],
  projectEndTime: [
    {
      required: true,
      message: '请选择结束时间',
      trigger: 'change',
    },
    { validator: validateEndTime, trigger: 'change' },
  ],
  projectStatus: [
    {
      required: true,
      message: '请选择项目状态',
      trigger: 'change',
    },
  ],
  studentParticipationCount: [
    {
      required: true,
      message: '请输入实验人数',
      trigger: 'blur',
    },
  ],
};



</script>

<style scoped>

.demo-form-inline {
  display: flex;
  align-items: center;
}
/* 定义不同状态下的 CSS 类 */
.el-switch-enabled {
  --el-switch-on-color: #13c75b;
  --el-switch-off-color: #13c75b;
}
.el-switch-disabled {
  --el-switch-on-color: #f56c6c;
  --el-switch-off-color: #f56c6c;
}
.pagination {
  margin-top: 20px;
}
.search {
  display: flex;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.search > form .el-form-item {
  flex-grow: 1;
  margin-right: 10px;
  margin-bottom: 0;
}
.action {
  margin-top: 10px;
  width: 100%;
  display: flex;
  padding: 10px 0;
  border-radius: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.1);
}
.dialog-footer {
  margin-top: 20px;
}
.data {
  margin-top: 5px;
  padding: 15px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}


.avatar {
  width: 120px;
  height: 120px;
  border: 1px solid #ccc;
}

.avatar .icon {
  width: 120px;
  height: 120px;
}

.avatar .preview {
  width: 120px;
  height: 120px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
}

.row-avatar {
  width: 50px;
  height: 50px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: contain;
  margin: 0 auto;
  border-radius: 50%; /* 设置为50%使头像为圆形 */
  overflow: hidden; /* 防止图片在圆外显示 */
}
/*卡片修饰*/
.grid {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.project-name {
  font-weight: bold;
  font-size: 16px;
}

.project-leader {
  font-size: 14px;
}

.project-introduction {
  height: 4em;
  margin-bottom: 10px;
  margin-top: 5px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.project-details {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 14px;
}

.project-details span {
  display: block;
  margin-bottom: 5px;
}

.project-details .participation {
  display: inline-block;
  font-size: 15px;
  margin-right: 10px; /* 可选：添加间距 */
}

.project-details .date-time {
  font-size: 14px; /* 字体小一点 */
  color: #999; /* 颜色浅一点 */
}

.project-actions {
  text-align: right;
}

/* 自定义按钮颜色 */
.custom-primary {
  background-color: #b388ff; /* 浅紫色 */
  border-color: #b388ff;
  color: #fff;
}

.custom-info {
  background-color: #64ffda; /* 浅青绿色 */
  border-color: #64ffda;
  color: #fff;
}

.custom-success {
  background-color: #ffc107; /* 浅橙色 */
  border-color: #ffc107;
  color: #fff;
}

.custom-danger {
  background-color: #ff5722; /* 浅红色 */
  border-color: #ff5722;
  color: #fff;
}
</style>
